﻿function getSelectedText(elementId) {
    var elt = document.getElementById(elementId);

    if (elt.selectedIndex == -1)
        return null;

    return elt.options[elt.selectedIndex].text;
}

function cambiaData(elementToShow) {
    document.getElementById("tab4_space").style.visibility = "hidden";
    document.getElementById("tab4_space_report").style.visibility = "hidden";
    document.getElementById(elementToShow).style.visibility = "visible";
}

function cambia(elementToShow) {
    document.getElementById("tab2_space_track").style.visibility = "hidden";
    document.getElementById("tab2_space_history").style.visibility = "hidden";
    document.getElementById(elementToShow).style.visibility = "visible";
    //display:none
}

window.onload = function () {
    callInquiryId(document.getElementById('listboxInquiryId').value, 'Secure/GetInquiryId');
    //NON VA QUI.. alimentata dopo selezione utente
    //getData();//NON VA QUI.. alimentata dopo selezione utente

};
var SelectedUser;
//attivata dalla select nel TAB INFO ... attiva il tab e la funzionalità richiesta
function chooseTab(element) {
    var tabChoosen = document.getElementById(element).value;
    CallAction(tabChoosen);

}

function CallAction(elementValue,idUtente , providerIdUtente) {
    SelectedUser = $('input[name="RadioButtonSelectedUser"]:checked').val();
    //alert(document.getElementById(element).value);
    /*
      Track -> tab2_space
      Show Path History  -> tab2_space
      Send Message  -> tab3_space
      Show Data -> tab4_space
      Assign Badges  -> tab5_space
     */
    if (elementValue == 'Track') {
        tab('tab2', 1);
        cleanMarker();
        //TO DO Deselezionare gli utenti ??
        GetUserMap('Secure/GetUserMap', 'UserOnMap', 'map_canvas', SelectedUser, document.getElementById('listboxInquiryId').value);
    }
    if (elementValue == 'Show Path History') {
        tab('tab2', 0);
        cleanMarker();
        GetUserHistoryMap('Secure/GetUserHistoryMap', 'UserOnMap', 'map_canvas', idUtente, providerIdUtente);
    }
    if (elementValue == 'Send Message') {
        tab('tab3');
        getThreadList('Secure/GetThreadList',document.getElementById('listboxInquiryId').value);
    }
    if (elementValue == 'Show Data') {
        tab('tab4');
        getUserData('Secure/GetUserData', document.getElementById('listboxInquiryId').value);
    }
    if (elementValue == 'Assign Badges') {
        tab('tab5');
        getUsersBadges('Secure/GetUsersBadges', document.getElementById('listboxInquiryId').value);
    }
}

//DATA
function getUserData(urlV, listboxInquiryId) {

    document.getElementById("tab4_space").innerHTML = "<div class=\"noInquiry\">No Inquiry Selected</div>";
    
    /*
    var dataForUser =
          '<data xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
          '<status type="integer">0</status>' +
          '<result type="array">' +
          '<array_item type="array">' +
          '<argomenti>' +
              '<argomento><label>Pictures</label><value>Pictures</value></argomento>' +
              '<argomento><label>Video</label><value>Video</value></argomento>' +
              '<argomento><label>Audio</label><value>Audio</value></argomento>' +
              '<argomento><label>Text</label><value>Text</value></argomento>' +
              '<argomento><label>Numeric</label><value>Numeric</value></argomento>' +
          '</argomenti>' +
          '<users>' +
  
          '<user>' +
          '<IdUtente>C</IdUtente>' +
          '<listaArgomenti>' +
              '<argomento>1</argomento>' +
              '<argomento>3</argomento>' +
              '<argomento>5</argomento>' +
              '<argomento>3</argomento>' +
              '<argomento>77</argomento>' +
          '</listaArgomenti>' +
          '<imageUser type="string">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1394697616&joindate=1394697606&guid=31125&size=medium</imageUser>' +
          '<userLat type="string"> 45.066866</userLat>' +
          '<userLon type="string">7.686740</userLon>' +
          '</user>' +
          '</users>' +
          '</array_item>' +
          '</result>' +
          '</data>';
          */
    if (document.getElementById('listboxInquiryId').value != "...") {
        document.getElementById("tab4_space").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";

        $.ajax({
            type: "GET",
            url: urlV,
            cache: false,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: { inquiryId: listboxInquiryId },
            success: function (response) {

                var testo = "";

                var data = $(response).find("argomenti");
                var user = $(response).find("user");

                testo += "<TABLE>";
                testo += "<TR>";

                if (data[0].childElementCount != 0) {
                    testo += "<TD  class='tdArgomenti'> &nbsp; </TD><TD></TD>"; // Intestazione USER - COlonna dedicata agli utenti
                    for (i = 0; i < data[0].childElementCount; i++) {

                        var label = data[0].childNodes[i].childNodes[0].innerText;
                        //var descr = data[0].childNodes[i].childNodes[1].innerText;
                        testo += "<TD class='tdArgomenti'>" + label + "</TD>";//+ "-" + value +
                    }
                    testo += "<TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>";
                    testo += "</TR>";
                    for (i = 0; i < user.length; i++) {

                        var idUtente = user[i].childNodes[0].textContent;
                        var userName = user[i].childNodes[1].textContent;
                        var listaArgomenti = user[i].childNodes[2];
                        var imageUser = user[i].childNodes[3].textContent;
                        var userLat = user[i].childNodes[4].textContent;
                        var userLon = user[i].childNodes[5].textContent;
                        testo += "<TR>";
                        testo += "<TD><img src='" + imageUser + "' height='35' width='35'></TD><TD style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 13px;font-weight: bold;\">" + userName + "</TD>"; //Sotto l'intestazione USER

                        for (j = 0; j < listaArgomenti.childNodes.length; j++) {
                            var value = listaArgomenti.childNodes[j].innerText;

                            testo += "<TD id='" + idUtente + "-" + value + "' style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 13px;font-weight: bold;\">" + value + "</TD>";

                            //else {
                            //    testo += "<TD id='" + idUtente + "-" + label + "-" + value + "' onclick=\"javascript:assignBadge('Secure/AssignBadge','" + idUtente + "','" + label + "','" + value + "')\";> Assign " + label + "</TD>";//+ "-" + value + " to user " + idUtente 
                            //}
                        }//onclick=\"javascript:printReport('Secure/printReport','" + idUtente + "');\"
                        testo += "<TD style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 15px;font-weight: bold;\">"+
                            "<A href='#' onclick=\"javascript:getReport('Secure/getReport','" + idUtente + "');\">View</A></TD>"+
                            "<TD style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 15px;font-weight: bold;\" >"+
                            "<A href='#' onclick=\"javascript:printReport('Secure/printReport','" + idUtente + "', " + document.getElementById('listboxInquiryId').value + ")\">Download </A></TD>";
                            testo += "</TR>";
}
                }
                else
                    testo += "<tr><td style=\"color:red;font-style:large;\">No Mobile data collection for this inquiry<td></tr>";
                testo += "</table>";

                document.getElementById("tab4_space").innerHTML = testo;
            }
        });
    }
}

function getReport(urlV, idUtenteV) {
    document.getElementById("tab4_space_report").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
    cambiaData("tab4_space_report");
    var listboxInquiryId = document.getElementById('listboxInquiryId').value;

    var timeValueTabDataV = document.getElementById("timeValueTabData").value;
    var select = document.getElementById("timeRangeTabData");
    var timeRangeTabDataV = select.options[select.selectedIndex].value;
    $.ajax({
        type: "GET",
        url: urlV,
        cache: false,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: { user: idUtenteV, timeRangeTabData: timeRangeTabDataV, timeValueTabData: timeValueTabDataV, inquiryId: listboxInquiryId },
        success: function (response) {
            var searchDate = $(response).find("searchDate");
            var array_item = $(response).find("action");
            var testo = " <a class='closeButton' id='closeButtonReport'></a><table>";

            //testo += "<tr><td colspan=\"2\" class=\"userHistoryText\">" + searchDate[0].childNodes[0].textContent + "</td></tr>"

            //+ "<startDate>" + searchDate + "</startDate>"
            //+ "<user>"
            //+ "<IdUtente>A</IdUtente>"
            //+ "<actions>"
            //+ "<action>"
            //+ "<actionType>tipo azione</actionType>"
            //+ "<actionDescription>desrizione dell azione</actionDescription>"
            //+ "<actionDate>24/02/2014</actionDate>"
            //+ "<actionImage type=\"string\">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium</actionImage>"
            //+ "<actionLat type=\"string\">45.066866</actionLat>"
            //+ "<actionLon type=\"string\">7.686740</actionrLon>"
            //+ "</action>"
            if (array_item.length != 0) {
                for (i = 0; i < array_item.length; i++) {
                    testo += "<tr class=\"userHistoryHeader\">";
                    var actionType = array_item[i].childNodes[0].textContent;
                    var actionDescription = array_item[i].childNodes[1].textContent;
                    var actionDate = array_item[i].childNodes[2].textContent;
                    var actionImage = array_item[i].childNodes[3].textContent;
                    var actionLat = array_item[i].childNodes[4].textContent;
                    var actionLon = array_item[i].childNodes[5].textContent;
                    testo +=

                         "<td style=\"color: red;font-size: large;\">" + actionDescription + "</td>" + "<td style=\"font-size: large;\">" + actionDate + "</td>";
                    testo += "</tr>";
                    testo += "<tr class=\"userHistoryText\">";
                    testo += "<TD>&nbsp;</TD> " + "<td>";
                    if (actionType == 'imageUrl') {
                        testo += "<img onclick=\"window.open('" + actionImage + "');\" src='" + actionImage + "?thumbnail=200&crop=true' onmouseover=\"littleThumb(this)\" onmouseout=\"normalThumb(this)\" height='72' width='72'></td>";
                    }
                    if (actionType == 'text' || actionType == 'value') {
                        testo += actionImage;
                    }
                    if (actionType == 'audioUrl') {
                        testo += "<audio controls>";
                        testo += "<source src=\"" + actionImage + "\" type=\"audio/mpeg\">";
                        testo += "<source src=\"" + actionImage + "\" type=\"audio/ogg\">";
                        testo += "  <embed height=\"50\" width=\"80\" src=\"" + actionImage + "\">";
                        testo += "</audio>";
                    }
                    if (actionType == 'videoUrl') {
                        testo += "<video width=\"80\" height=\"80\" controls>";
                        testo += "  <source src=" + actionImage + " type=\"video/mp4\">";
                        testo += "  <object data=" + actionImage + " width=\"80\" height=\"80\">";
                        testo += "    <embed src=" + actionImage + " width=\"80\" height=\"80\">";
                        testo += "  </object> ";
                        testo += "</video>";
                    }


                    // "<td>" + actionImage + "</td>" +
                    // "<td>" + actionLat + "</td>" +
                    // "<td>" + actionLon + "</td>"
                    //AddHistoryPointToMap('map_canvas', actionLat, actionLon, actionImage,actionType);
                    testo += "</tr>";
                }
            }
            else {
                testo += "<TR style=\"border-bottom: 1pt solid red;display:block;\">";
                testo += "<TD style=\"color:red;font-style:large;\">&nbsp; No data - date filter : " + searchDate[0].childNodes[0].textContent + "</TD>";
                testo += "</TR>";
            }
               

            testo += "</table>";

            document.getElementById("tab4_space_report").innerHTML = testo;
            document.getElementById('closeButtonReport').onclick = function () {
                cambiaData("tab4_space");
                return false;
            };
            
            //CallAction("tab4_space_report");
        }
    });
}

                    
function printReport(urlV,idUtenteV,listboxInquiryIdV) {

/*
    urlV = "Secure/printReport";
    $.ajax({
        type: "GET",
        url: urlV,
        cache: false,
        contentType: 'application/octet-stream',
        data: { user: idUtenteV, timeRangeTabData: "sss", timeValueTabData: "sss" },
        success: function (response) {
            alert(response);
        }
    });
 */
    var test = urlV + "?user=" + idUtenteV+ "&timeRangeTabData=" + document.getElementById("timeRangeTabData").value + "&timeValueTabData=" + document.getElementById("timeValueTabData").value + "&inquiryId=" + listboxInquiryIdV;

    //var test = "http://massimo.serveftp.com/Secure/printReport?user=" + idUtenteV + "&timeRangeTabData=" + "idUtenteV" + "&timeValueTabData=" + "idUtenteV";

    window.open(test, "downloadfile");
}

//BADGES
function getUsersBadges(urlV, listboxInquiryId) {
    document.getElementById("tab5_space").innerHTML = "<div class=\"noInquiry\">No Inquiry Selected</div>";


    if (document.getElementById('listboxInquiryId').value != "...") {
        document.getElementById("tab5_space").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";

        /*
         var badges_dummy =
             '<medaglie xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
             '<status type="integer">0</status>' +
             '<result type="array">' +
             '<array_item type="array">' +
             '<argomenti>' +
                 '<argomento><label>Uno</label><value>Uno V</value></argomento>' +
                 '<argomento><label>Due</label><value>Due V</value></argomento>' +
                 '<argomento><label>Tre</label><value>Tre V</value></argomento>' +
             '</argomenti>' +
             '<users>' +
             '<user>' +
             '<IdUtente>C</IdUtente>' +
             '<listaMedaglie>' +
             '</listaMedaglie>' +
             '<imageUser type="string">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1394697616&joindate=1394697606&guid=31125&size=medium</imageUser>' +
             '<userLat type="string"> 45.066866</userLat>' +
             '<userLon type="string">7.686740</userLon>' +
             '</user>' +
             '</users>' +
             '</array_item>' +
             '</result>' +
             '</medaglie>';
           */
        $.ajax({
            type: "GET",
            url: urlV,
            cache: false,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: { inquiryId: listboxInquiryId },
            success: function (response) {
                var testo = "";

                
                var badges = $(response).find("argomento");
                var user = $(response).find("user");
                if (badges.length != 0) {
                    testo += "<TABLE>";
                    testo += "<TR>";
                    testo += "<TD>&nbsp;&nbsp;&nbsp;</TD><TD>&nbsp;&nbsp;&nbsp;</TD>"; // Intestazione USER - COlonna dedicata agli utenti
                    for (i = 0; i < badges.length; i++) {
                        var badgeId = badges[i].childNodes[0].textContent;
                        var badgeLabel = badges[i].childNodes[1].textContent;
                        var badgeImage = badges[i].childNodes[2].textContent;
                        testo += "<TD align=\"center\" width=\"50px\" ><IMG src=\"" + badgeImage + "\" title=\"" + badgeLabel + "\" alt=\"" + badgeLabel + "\" height=\"35\" width=\"35\"></TD>";
                    }
                    testo += "</TR>";

                    for (i = 0; i < user.length; i++) {

                        var idUtente = user[i].childNodes[0].textContent;
                        var listaMedaglie = user[i].childNodes[1];
                        var imageUser = user[i].childNodes[2].textContent;
                        var username = user[i].childNodes[3].textContent
                        var userLat = user[i].childNodes[4].textContent;
                        var userLon = user[i].childNodes[5].textContent;

                        testo += "<TR>";
                        testo += "<TD><img src='" + imageUser + "' height='35' width='35'></TD><TD style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 13px;font-weight: bold;\">" + username + "</TD>"; //Sotto l'intestazione USER

                        for (j = 0; j < badges.length; j++) {
                            var badgeId = badges[j].childNodes[0].textContent;
                            var badgeLabel = badges[j].childNodes[1].textContent;
                            var badgeImage = badges[j].childNodes[2].textContent;

                            if (assignedBadge(listaMedaglie, badgeId)) {
                                testo += "<TD  align=\"center\" width=\"50px\" id='" + idUtente + "-" + badgeId + "'><img src=\"./images/tick.png\" alt=\"Assign award\" title=\"Assigned award\" height=\"35\" width=\"35\"></TD>";
                            }
                            else {
                                testo += "<TD  align=\"center\" width=\"50px\" id='" + idUtente + "-" + badgeId + "' onclick=\"javascript:assignBadge('Secure/AssignBadge','" + badgeId + "','" + badgeLabel + "','" + "WeSpot" + "','" + idUtente + "','" + username + "')\";><div style=\"background-color:white;height:35px;width:35px;\"></div></TD>";
                                //<img onmouseover=\"littleImg(this)\" onmouseout=\"normalImg(this)\" src=\"./images/coccarda.jpg\" alt=\"Assign award\" title=\"Assign award\" height=\"35\" width=\"35\">
                            }
                        }
                        testo += "</TR>";
                    }
                }
                else
                    testo += "<tr><td style=\"color:red;font-style:large;\">No Badges available for this inquiry<td></tr>";
                testo += "</table>";

                document.getElementById("tab5_space").innerHTML = testo;

            }
        });
    }
        
}

function assignedBadge(listaMedaglie, badge) {
    var i = 0;
    for (i = 0; i < listaMedaglie.childElementCount; i++) {
        if (listaMedaglie.childNodes[i].innerText == badge)
            return true;
    }
    return false;
}
//string BadgeId, string provider, string oauthId, string inquiryId
//,             user: idUtenteV, badgeLabel: labelV, badgeValue: valueV
function assignBadge(urlV, badgeIdV, badgeLabelV, providerV, idUtenteV, usernameV) {
    var r = confirm("Please confirm that you want to assign  \"" + badgeLabelV + "\" Badge  to " + usernameV);
    if (r == true) {
        //alert(idUtenteV + "-" + labelV + "-" + valueV);
        $.ajax({
            type: "GET",
            url: urlV,
            cache: false,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: { BadgeId: badgeIdV, provider: providerV, oauthId: idUtenteV },
            success: function (response) {
                //alert(response);
                document.getElementById(idUtenteV + "-" + badgeIdV).innerHTML = "<img src=\"./images/tick.png\" alt=\"" + badgeLabelV + "\" title=\"" + badgeLabelV + "\" height=\"35\" width=\"35\">";
                //document.getElementById(idUtenteV + "-" + labelV + "-" + valueV).innerHTML = labelV + " Assigned";//+ " - " + valueV + "to " + idUtenteV
                document.getElementById(idUtenteV + "-" + badgeIdV).onclick = null;
            }
        });
    } else {
        ;
    }

}

function getThreadList(urlV, listboxInquiryId) {
    document.getElementById("tab3_listThread").innerHTML = "<div class=\"noInquiry\">No Inquiry Selected</div>";
    
    //alert(inquiryId + " " + url);
    if (document.getElementById('listboxInquiryId').value != "...") {
        document.getElementById("tab3_listThread").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";

        $.ajax({
            type: "GET",
            url: urlV,
            cache: false,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: { inquiryId: listboxInquiryId },
            success: function (response) {
                var testo = "";
                testo += "<TABLE>";

                var inquiryRunId = $(response).find("runId");
                var hiddenInquiryRunId = document.getElementById("runIdThread");
                hiddenInquiryRunId.value = inquiryRunId[0].childNodes[0].textContent;


                var user = $(response).find("user");


                var IdUtente = user[0].childNodes[0].textContent;
                var IdUtenteProvider = user[0].childNodes[1].textContent;
                var username = user[0].childNodes[2].textContent;


                var provider = document.getElementById("provider");
                provider.value = IdUtenteProvider;

                var oauth = document.getElementById("oauth");
                oauth.value = IdUtente;

                testo += "<TR>";
                //testo += "<TD>&nbsp;</TD><TD style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 15px;font-weight: bold;\">" + username + "</TD><TD>&nbsp;</TD>";
                testo += "<TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>";
                testo += "</TR>";

                var thread = $(response).find("thread");


                var DefaultThreadId;
                if (thread.length != 0) {
                    for (i = 0; i < thread.length; i++) {


                        var runId = thread[i].childNodes[0].textContent;
                        var threadId = thread[i].childNodes[1].textContent;

                        //WARNING substitution of the Thread Selection Button Action -> Only one thread will be showed
                        var selectedThreadId = document.getElementById("selectedThreadId");
                        selectedThreadId.value = threadId;

                        DefaultThreadId = threadId;

                        var name = thread[i].childNodes[2].textContent;
                        var deleted = thread[i].childNodes[3].textContent;
                        var lastModification = thread[i].childNodes[4].textContent;

                        testo += "<TR>";
                        //testo += "<TD><img onmouseover=\"littleImg(this)\" onmouseout=\"normalImg(this)\"  src=\"Content/images/close-button.png\" onclick=\"javascript:deleteThread('Secure/DeleteThread','" + threadId + "','" + document.getElementById('listboxInquiryId').value + "');\" height=\"35\" width=\"35\"/></TD><TD>" + "<DIV id=\"threadBox_" + threadId + "\" onclick=\"javascript:getThreadMessages('Secure/GetThreadMessages','" + threadId + "');\" onmouseover=\"littleDiv(this)\" onmouseout=\"normalDiv(this)\" style=\"vertical-align:middle;height:50px;width:80px;background-color:#AAA;color:white;text-align:center;font-family:Helvetica, Arial, sans-serif;border-radius:4px;\">" + name + "</DIV>" + "</TD><TD style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 13px;font-weight: bold;\">" + lastModification + "</TD>";
                        testo += "<TD>&nbsp;</TD><TD>" + "<DIV id=\"threadBox_" + threadId + "\" onclick=\"javascript:getThreadMessages('Secure/GetThreadMessages','" + threadId + "');\" onmouseover=\"littleDiv(this)\" onmouseout=\"normalDiv(this)\" style=\"vertical-align:middle;height:50px;width:110px;background-color:#AAA;color:white;text-align:center;font-family:Helvetica, Arial, sans-serif;border-radius:4px;\">" + name + "</DIV>" + "</TD><TD style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 13px;font-weight: bold;\">" + lastModification + "</TD>";
                        testo += "</TR>";

                    }
                }
                else
                    testo += "<tr><td style=\"color:red;font-style:large;\">No Mobile data collection for this inquiry<td></tr>";
                testo += "</TABLE>";

                document.getElementById("tab3_listThread").innerHTML = testo;

                //WARNING substitution of the Thread Selection Button Action -> Only one thread will be showed
                getThreadMessages('Secure/GetThreadMessages', DefaultThreadId );
                }
        });
    }

}

function deleteThread(urlV, threadIdV, listboxInquiryIdV)
{
    $.ajax({
        type: "GET",
        url: urlV,
        cache: false,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: { threadId: threadIdV, inquiryId: listboxInquiryIdV },
        success: function (response) {
            var testo = "";
            testo += "<TABLE>";

            var inquiryRunId = $(response).find("runId");
            var hiddenInquiryRunId = document.getElementById("runIdThread");
            hiddenInquiryRunId.value = inquiryRunId[0].childNodes[0].textContent;


            var user = $(response).find("user");


            var IdUtente = user[0].childNodes[0].textContent;
            var IdUtenteProvider = user[0].childNodes[1].textContent;
            var username = user[0].childNodes[2].textContent;


            var provider = document.getElementById("provider");
            provider.value = IdUtenteProvider;

            var oauth = document.getElementById("oauth");
            oauth.value = IdUtente;

            testo += "<TR>";
            //testo += "<TD>&nbsp;</TD><TD>" + username + "</TD><TD>&nbsp;</TD>";
            testo += "<TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>";
            testo += "</TR>";

            var thread = $(response).find("thread");




            for (i = 0; i < thread.length; i++) {


                var runId = thread[i].childNodes[0].textContent;
                var threadId = thread[i].childNodes[1].textContent;
                var name = thread[i].childNodes[2].textContent;
                var deleted = thread[i].childNodes[3].textContent;
                var lastModification = thread[i].childNodes[4].textContent;

                testo += "<TR>";
                //testo += "<TD><img onmouseover=\"littleImg(this)\" onmouseout=\"normalImg(this)\" src=\"Content/images/close-button.png\" onclick=\"javascript:deleteThread('Secure/DeleteThread','" + threadId + "','" + document.getElementById('listboxInquiryId').value + "');\" height=\"35\" width=\"35\"/></TD><TD>" + "<DIV onclick=\"javascript:getThreadMessages('Secure/GetThreadMessages','" + threadId + "');\" onmouseover=\"littleDiv(this)\" onmouseout=\"normalDiv(this)\" style=\"vertical-align:middle;height:50px;width:80px;background-color:#AAA;color:white;text-align:center;font-family:Helvetica, Arial, sans-serif;border-radius:4px;\">" + name + "</DIV>" + "</TD><TD>" + lastModification + "</TD>";
                testo += "<TD>&nbsp;</TD><TD>" + "<DIV onclick=\"javascript:getThreadMessages('Secure/GetThreadMessages','" + threadId + "');\" onmouseover=\"littleDiv(this)\" onmouseout=\"normalDiv(this)\" style=\"vertical-align:middle;height:50px;width:80px;background-color:#AAA;color:white;text-align:center;font-family:Helvetica, Arial, sans-serif;border-radius:4px;\">" + name + "</DIV>" + "</TD><TD>" + lastModification + "</TD>";
                testo += "</TR>";
            }
            testo += "</TABLE>";

            document.getElementById("tab3_listThread").innerHTML = testo;
        }
    });
}

function getThreadMessages(urlV, threadIdV)
{
    document.getElementById("tab3_ThreadMessage").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
    //document.getElementById("tab3_ThreadMessage").innerHTML = "<TABLE width=\"100%\" height=\"100%\"><tr><td><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;\"></td></tr></table>";
    var divList = document.querySelectorAll('[id^=threadBox_]');
    for (iDiv = 0; iDiv < divList.length; iDiv++)
    {
        divList[iDiv].style.backgroundColor = 'rgb(170, 170, 170)';
    }
    document.getElementById("threadBox_" + threadIdV).style.backgroundColor = 'rgb(90, 138, 198)';
    var selectedThreadId = document.getElementById("selectedThreadId");
    selectedThreadId.value = threadIdV;

    $.ajax({
        type: "GET",
        url: urlV,
        cache: false,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: { threadId: threadIdV },
        success: function (response) {
            var testo = "";

            /*
            <message>
                <messageMessageId>
                <messageRunId>
                <messageThreadId>
                <messageDate>
                <messageBody>
                <messageSenderId>
                <messageSenderProviderId>
            </message>
            */
            testo += "<TABLE width=\"100%\">";
            var messages = $(response).find("message");
            if (messages.length == 0)
            {
                testo += "<TR style=\"border-bottom: 1pt solid red;display:block;\">";
                testo += "<TD style=\"color:rgb(90, 138, 198);font-style:large;\"></TD>" + "<TD style=\"color:red;font-style:large;\">&nbsp; No messages</TD>";
                testo += "</TR>";
            }
            for (i = 0; i < messages.length; i++) {

                var messageMessageId = messages[i].childNodes[0].textContent;
                var messageRunId = messages[i].childNodes[1].textContent;
                var messageThreadId = messages[i].childNodes[2].textContent;
                var messageDate = messages[i].childNodes[3].textContent;
                var messageBody = messages[i].childNodes[4].textContent;
                var messageSenderId = messages[i].childNodes[5].textContent;
                var messageSenderProviderId = messages[i].childNodes[6].textContent;
                var messageUserName = messages[i].childNodes[7].textContent;
                var messageUserIcon = messages[i].childNodes[8].textContent;

                if (i % 2) {
                    testo += "<TR style=\"border-bottom: 1pt solid red;display:block;\">";
                }
                else {
                    testo += "<TR style=\"background:rgb(253,255,175);border-bottom: 1pt solid red;display:block;\">";
                }

                testo += "<TD style=\"color:rgb(90, 138, 198);font-style:large;\"><img src=\"" + messageUserIcon + "\" style=\"width: 35px; height: 35px; vertical-align: middle;\">" + messageUserName + "        -        " + messageDate + "</BR><span style=\"color:red;font-style:large;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + messageBody + "</span></TD>";
                testo += "</TR>";
            }
            testo += "</TABLE>";

            document.getElementById("tab3_ThreadMessage").innerHTML = testo;
        }
    });
}

function preCreateMessage(urlV)
{
    var hiddenInquiryRunId = document.getElementById("runIdThread");
    var runIdV = hiddenInquiryRunId.value;

    //var newThreadName = document.getElementById("newThreadName");
    var treadNameV = "Default"; //newThreadName.value;

    var provider = document.getElementById("provider");
    var providerV = provider.value;

    var oauth = document.getElementById("oauth");
    var oauthV = oauth.value;

    var inquiryIdV = document.getElementById('listboxInquiryId').value;

    var selectedThreadId = document.getElementById("selectedThreadId");
    var selectedThreadIdV = selectedThreadId.value;

    /*
    var newThreadSubject = document.getElementById("newThreadSubject");
    var newThreadSubjectV = newThreadSubject.value;
    */
    var newThreadSubjectV = treadNameV;

    var newThreadMessage = document.getElementById("newThreadMessage");
    var newThreadMessageV = newThreadMessage.value;
     //runId,  ThreadIdString,  subjectString,  bodyString,  userId,  provider,  oauth,  inquiryId
    createMessage(urlV, runIdV, selectedThreadIdV,newThreadSubjectV, newThreadMessageV, oauthV, providerV, oauthV, inquiryIdV)
}

function createMessage(urlV, runIdV, selectedThreadIdV, subjectStringV, bodyStringV, userId, providerV, oauthV, inquiryIdV)
{
               //runId,  ThreadIdString,  subjectString,  bodyString,  userId,  provider,  oauth,  inquiryId
    $.ajax({
        type: "GET",
        url: urlV,
        cache: false,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: { runId: runIdV, ThreadIdString: selectedThreadIdV, subjectString: subjectStringV, bodyString: bodyStringV, userId: userId, provider: providerV, oauth: oauthV, inquiryId: inquiryIdV },
        success: function (response) {
            var testo = "";

            /*
            <message>
                <messageMessageId>
                <messageRunId>
                <messageThreadId>
                <messageDate>
                <messageBody>
                <messageSenderId>
                <messageSenderProviderId>
            </message>
            */
            testo += "<TABLE width=\"100%\">";
            var messages = $(response).find("message");

            for (i = 0; i < messages.length; i++) {

                var messageMessageId = messages[i].childNodes[0].textContent;
                var messageRunId = messages[i].childNodes[1].textContent;
                var messageThreadId = messages[i].childNodes[2].textContent;
                var messageDate = messages[i].childNodes[3].textContent;
                var messageBody = messages[i].childNodes[4].textContent;
                var messageSenderId = messages[i].childNodes[5].textContent;
                var messageSenderProviderId = messages[i].childNodes[6].textContent;
                var messageUserName = messages[i].childNodes[7].textContent;
                var messageUserIcon = messages[i].childNodes[8].textContent;

                testo += "<TR style=\"border-bottom: 1pt solid red;display:block;\">";
                testo += "<TD style=\"color:rgb(90, 138, 198);font-style:large;\"><img src=\"" + messageUserIcon + "\" style=\"width: 35px; height: 35px; vertical-align: middle;\">" + messageUserName + "</TD>" + "<TD style=\"color:red;font-style:large;\">&nbsp;" + messageBody + "</TD>";
                testo += "</TR>";
            }
            testo += "</TABLE>";

            document.getElementById("tab3_ThreadMessage").innerHTML = testo;
            var newThreadMessage = document.getElementById("newThreadMessage");
            newThreadMessage.value = "";
        }
            
    });
}

function preCreateThread(urlV)
{
    var hiddenInquiryRunId = document.getElementById("runIdThread");
    var runIdV = hiddenInquiryRunId.value;

    var newThreadName = document.getElementById("newThreadName");
    var treadNameV = newThreadName.value;

    var provider = document.getElementById("provider");
    var providerV = provider.value;

    var oauth = document.getElementById("oauth");
    var oauthV = oauth.value;

    var inquiryIdV = document.getElementById('listboxInquiryId').value;
    var x;
    if (confirm("Creating " + treadNameV + " ...") == true) {
        createThread(urlV, runIdV, treadNameV, providerV, oauthV, inquiryIdV);
    } else {
        ;
    }

    
}

function createThread(urlV, runIdV, treadNameV, providerV, oauthV, inquiryIdV)
{
    if (treadNameV != "") {
        document.getElementById("tab3_listThread").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";

        $.ajax({
            type: "GET",
            url: urlV,
            cache: false,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: { runId: runIdV, treadName: treadNameV, provider: providerV, oauth: oauthV, inquiryId: inquiryIdV },
            success: function (response) {
                var testo = "";
                testo += "<TABLE>";

                var inquiryRunId = $(response).find("runId");
                var hiddenInquiryRunId = document.getElementById("runIdThread");
                hiddenInquiryRunId.value = inquiryRunId[0].childNodes[0].textContent;


                var user = $(response).find("user");


                var IdUtente = user[0].childNodes[0].textContent;
                var IdUtenteProvider = user[0].childNodes[1].textContent;
                var username = user[0].childNodes[2].textContent;


                var provider = document.getElementById("provider");
                provider.value = IdUtenteProvider;

                var oauth = document.getElementById("oauth");
                oauth.value = IdUtente;

                testo += "<TR>";
                //testo += "<TD>&nbsp;</TD><TD>" + username + "</TD><TD>&nbsp;</TD>";
                testo += "<TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>";
                testo += "</TR>";

                var thread = $(response).find("thread");




                for (i = 0; i < thread.length; i++) {


                    var runId = thread[i].childNodes[0].textContent;
                    var threadId = thread[i].childNodes[1].textContent;
                    var name = thread[i].childNodes[2].textContent;
                    var deleted = thread[i].childNodes[3].textContent;
                    var lastModification = thread[i].childNodes[4].textContent;

                    testo += "<TR>";
                    //testo += "<TD><img onmouseover=\"littleImg(this)\" onmouseout=\"normalImg(this)\"  src=\"Content/images/close-button.png\" onclick=\"javascript:deleteThread('Secure/DeleteThread','" + threadId + "','" + document.getElementById('listboxInquiryId').value + "');\" height=\"35\" width=\"35\"/></TD><TD>" + "<DIV id=\"threadBox_" + threadId + "\" onclick=\"javascript:getThreadMessages('Secure/GetThreadMessages','" + threadId + "');\" onmouseover=\"littleDiv(this)\" onmouseout=\"normalDiv(this)\" style=\"vertical-align:middle;height:50px;width:80px;background-color:#AAA;color:white;text-align:center;font-family:Helvetica, Arial, sans-serif;border-radius:4px;\">" + name + "</DIV>" + "</TD><TD>" + lastModification + "</TD>";
                    testo += "<TD>&nbsp;</TD><TD>" + "<DIV id=\"threadBox_" + threadId + "\" onclick=\"javascript:getThreadMessages('Secure/GetThreadMessages','" + threadId + "');\" onmouseover=\"littleDiv(this)\" onmouseout=\"normalDiv(this)\" style=\"vertical-align:middle;height:50px;width:80px;background-color:#AAA;color:white;text-align:center;font-family:Helvetica, Arial, sans-serif;border-radius:4px;\">" + name + "</DIV>" + "</TD><TD>" + lastModification + "</TD>";
                    testo += "</TR>";
                }
                testo += "</TABLE>";

                document.getElementById("tab3_listThread").innerHTML = testo;
                var newThreadName = document.getElementById("newThreadName");
                newThreadName.value = "";
            }
        });
    }
    else
        alert("Please, insert a Thread name.");
}

function getUserRunResponses(inquiryId, oauthid, oauthprovider, url) {
    //document.getElementById("tab3_ThreadMessage").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";

    //alert(inquiryId + " " + oauthid + " " + oauthprovider + url);
    $.ajax({
        type: "GET",
        url: url,
        cache: false,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: "",
        success: function (response) {
            //var array_item = $(response).find("array_item");
            //<array_item type="array">
            //<oauthid type="string">642859267</oauthid>
            //<oauthprovider type="string">Facebook</oauthprovider>
            //<name type="string">Enrico Bruzzone</name>
            //</array_item>
            //for (i = 0; i < array_item.length; i++) {
            //    testo += "<tr>";

            //    var oauthid = array_item[i].childNodes[0].textContent;
            //    var oauthprovider = array_item[i].childNodes[1].textContent;
            //    var name = array_item[i].childNodes[2].textContent;
            //    var icon = array_item[i].childNodes[3].textContent;
            //    testo += "<td><img onclick=\"javascript:GetUserRunResponses(document.getElementById('listboxInquiryId').value,'" + oauthid + "','" + oauthprovider + "');\" src='" + icon + "' height='20' width='20'> </td> " + "<td>" + name + " </td> ";
            //    testo += "</tr>";
            //}
        }
    });
    //document.getElementById("tab1_descr").innerHTML = inquiryIdToDescription[value];
}

//Crea la tabella con la lista degli utenti. Tabella inserita nel TAB Track
//GetUserMap('Secure/GetUserMap',UserOnMap,map_canvas);
function GetUserMap(url, checkBoxGroupName, mapName, SelectedUser, listboxInquiryId) {
    document.getElementById("tab2_space_Users_track").innerHTML = "<div class=\"noInquiry\">No Inquiry Selected</div>";

    if (document.getElementById('listboxInquiryId').value != "...") {
        document.getElementById("tab2_space_Users_track").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        $.ajax({
            type: "GET",
            url: url,
            cache: false,
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: { inquiryId: listboxInquiryId },
            success: function (response) {
                var array_item = $(response).find("users");
                var testo = "<table>";

                //<array_item type="array">
                //<users>
                //<IdUtente>A</IdUtente>
                //<imageUser type="string">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1395242006&joindate=1395242004&guid=31560&size=medium</imageUser>
                //<userLat type="string">44.405658</userLat>
                //<userLon type="string">8.952934</userLon>
                //</users>
                //<users>
                //<IdUtente>B</IdUtente>
                //<imageUser type="string">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1394697616&joindate=1394697606&guid=31125&size=medium</imageUser>
                //<userLat type="string"> 45.066866</userLat>
                //<userLon type="string">7.686740</userLon>
                //</users>
                //<users>
                //<IdUtente>C</IdUtente>
                //<imageUser type="string">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium</imageUser>
                //<userLat type="string">45.458819</userLat>
                //<userLon type="string">9.173395</userLon>
                //</users>
                //</array_item>
                if (array_item.length != 0) {
                    for (i = 0; i < array_item.length; i++) {
                        testo += "<tr>";
                        var idUtente = array_item[i].childNodes[0].textContent;
                        var providerIdUtente = array_item[i].childNodes[1].textContent;
                        var userName = array_item[i].childNodes[2].textContent;
                        var imageUser = array_item[i].childNodes[3].textContent;
                        var userLat = array_item[i].childNodes[4].textContent;
                        var userLon = array_item[i].childNodes[5].textContent;

                        testo += "<td><img src=\"" + imageUser + "\" width=\"30\" height=\"30\" /></td><td><input type='checkbox' name='" + checkBoxGroupName + "' id='" + idUtente.split(' ').join("_") + "' onclick=\"AddUserToMap('" + mapName + "'," + userLat + "," + userLon + ",'" + imageUser + "','" + idUtente.split(' ').join("_") + "', '" + idUtente + "','" + userName + "');\"></td><td style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 13px;font-weight: bold;\">" + userName + "</td><td><DIV onclick=\"javascript:UserHistoryMap('" + idUtente + "','" + providerIdUtente + "');\" onmouseover=\"littleDiv(this)\" onmouseout=\"normalDiv(this)\" style=\"vertical-align:middle;height:50px;width:80px;background-color:#AAA;color:white;text-align:center;font-family:Helvetica, Arial, sans-serif;border-radius:4px;\">Path History</DIV></td>";
                        testo += "</tr>";
                    }
                }
                else
                    testo += "<tr><td style=\"color:red;font-style:large;\">No Mobile data collection for this inquiry<td></tr>"
                testo += "</table>";
                document.getElementById("tab2_space_Users_track").innerHTML = testo;
            }
        });
    }
    /*
    <table>
        <tr><td>Marker</td><td>View</td><td>Utente</td><td>Locazione</td><td>Percorso</td></tr>
        <tr><td><img src="http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1395242006&joindate=1395242004&guid=31560&size=medium" width="20" height="20" /></td><td><input type="checkbox" name="UserOnMap" value="IdUtente1" id="IdUtente1" onclick="AddUserToMap('map_canvas', 44.405658, 8.952934, 'http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1395242006&joindate=1395242004&guid=31560&size=medium', 'IdUtente1');"></td><td>Utente 1</td><td><img src="./uno.jpg" width="20" height="20" onclick="loadMapUser('map_canvas',44.405658, 8.952934);"></td><td></td></tr>
        <tr><td><img src="http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1394697616&joindate=1394697606&guid=31125&size=medium" width="20" height="20" /></td><td><input type="checkbox" name="UserOnMap" value="IdUtente2" id="IdUtente2" onclick="AddUserToMap('map_canvas', 45.066866, 7.686740, 'http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1394697616&joindate=1394697606&guid=31125&size=medium', 'IdUtente2');"></td><td>Utente 2</td><td><img src="./uno.jpg" width="20" height="20" onclick="loadMapUser('map_canvas',45.066866, 7.686740);"></td><td></td></tr>
        <tr><td><img src="http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium" width="20" height="20" /></td><td><input type="checkbox" name="UserOnMap" value="IdUtente3" id="IdUtente3" onclick="AddUserToMap('map_canvas', 45.458819, 9.173395, 'http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium', 'IdUtente3');"></td><td>Utente 3</td><td><img src="./uno.jpg" width="20" height="20" onclick="loadMapUser('map_canvas',45.458819, 9.173395);"></td><td></td></tr>
        <tr><td>--</td><td>--</td><td>Percorso</td><td><img src="./uno.jpg" width="20" height="20" onclick="settaImmagine('map_canvas', 47.35387, 8.43609);"></td><td></td></tr>
    </table>
  */
}

//Costruisce la lista dei punti e stampa la tabella e valorizza la mappa
function GetUserHistoryMap(urlV, checkBoxGroupName, mapName, listboxInquiryId, idUtenteV, providerIdUtenteV, dataFromV) {
    document.getElementById("tab2_space_Users_history").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";

    $.ajax({
        type: "GET",
        url: urlV,
        cache: false,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: { inquiryId : listboxInquiryId, idUtente : idUtenteV, providerIdUtente : providerIdUtenteV, dataFrom : dataFromV},
        success: function (response) {
            var array_item = $(response).find("action");
            var testo = "<table>";
            //+ "<user>"
            //+ "<IdUtente>A</IdUtente>"
            //+ "<actions>"
            //+ "<action>"
            //+ "<actionType>tipo azione</actionType>"
            //+ "<actionDescription>desrizione dell azione</actionDescription>"
            //+ "<actionDate>24/02/2014</actionDate>"
            //+ "<actionImage type=\"string\">http://inquiry.wespot.net/mod/profile/icondirect.php?lastcache=1391006002&joindate=1391006001&guid=27975&size=medium</actionImage>"
            //+ "<actionLat type=\"string\">45.066866</actionLat>"
            //+ "<actionLon type=\"string\">7.686740</actionrLon>"
            //+ "</action>"
            for (i = 0; i < array_item.length; i++) {
                testo += "<tr class=\"userHistoryHeader\">";
                var actionType = array_item[i].childNodes[0].textContent;
                var actionDescription = array_item[i].childNodes[1].textContent;
                var actionDate = array_item[i].childNodes[2].textContent;
                var actionImage = array_item[i].childNodes[3].textContent;
                var actionLat = array_item[i].childNodes[4].textContent;
                var actionLon = array_item[i].childNodes[5].textContent;
                testo += "<td style=\"color: red;font-size: large;\"> " + i + "</td>" + "<td style=\"font-size: large;\">" + actionDescription + "</td>";

                     //"<td>" + actionType + "</td>" + "<td>" + actionDate + "</td>";
                testo += "</tr>";
                testo += "<tr class=\"userHistoryText\">";

                if (actionType == "imageUrl")
                    testo += "<TD>&nbsp;</TD> " + "<td><img src=\"" + actionImage + "\"  width=\"30\" height=\"30\" /></td>";
                if (actionType == "videoUrl") {
                    testo += "<TD>&nbsp;</TD> " + "<td>";
                    testo += "<video width=\"80\" height=\"80\" controls>";
                    testo += "  <source src=" + actionImage + " type=\"video/mp4\">";
                    testo += "  <object data=" + actionImage + " width=\"80\" height=\"80\">";
                    testo += "    <embed src=" + actionImage + " width=\"80\" height=\"80\">";
                    testo += "  </object> ";
                    testo += "</video>";
                    testo += "</td>";
                }
                if (actionType == "text")
                    testo += "<TD>&nbsp;</TD> " + "<td>" + actionImage + "</td>";
                if (actionType == "audioUrl") {
                    testo += "<TD>&nbsp;</TD> " + "<td>";
                    testo += "<audio controls>";
                    testo +=   "<source src=\"" + actionImage+ "\" type=\"audio/mpeg\">";
                    testo +=   "<source src=\"" + actionImage + "\" type=\"audio/ogg\">";
                    testo += "  <embed height=\"50\" width=\"80\" src=\"" + actionImage + "\">";
                    testo +=   "</audio>";
                    testo += "</td>";
                }
                if (actionType == "value")
                    testo += "<TD>&nbsp;</TD> " + "<td>" + actionImage + "</td>";


                // "<td>" + actionImage + "</td>" +
                // "<td>" + actionLat + "</td>" +
                // "<td>" + actionLon + "</td>"
                
                AddHistoryPointToMap('map_canvas', actionLat, actionLon, actionImage, actionDescription, i);
                testo += "</tr>";
            }
            testo += "</table>";
            document.getElementById("tab2_space_Users_history").innerHTML = testo;
        }
    });
}


function GetUserMail(urlV,oauthIdV, oauthProviderV)
{
    return $.ajax({
        type: "GET",
        url: urlV,
        cache: false,
        async: false,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: { oauthId : oauthIdV, oauthProvider : oauthProviderV },
        //success: function (response) {
            //var array_item = $(response).find("array_item");
            //<array_item type="array">
            //<oauthid type="string">642859267</oauthid>
            //<oauthprovider type="string">Facebook</oauthprovider>
            //<name type="string">Enrico Bruzzone</name>
            //</array_item>
                //var oauthid = array_item[i].childNodes[0].textContent;
                //var oauthprovider = array_item[i].childNodes[1].textContent;
                //var name = array_item[i].childNodes[2].textContent;
            //var icon = array_item[i].childNodes[3].textContent;
            //if (array_item.length == 0)
            //    return "#";
            //var mail = array_item[0].childNodes[0].textContent;
            //    return mail;
            
        //    return "" + response;
        //    }
    });
}
//Crea la tabella con la lista degli utenti. Tabella inserita nel TAB INFO
//Valorizza in campo Info del TAB INFO
function callInquiryId(value, url) {
    document.getElementById("tab1_space").innerHTML = "<div class=\"noInquiry\">No Inquiry Selected</div>";
    if (value != "...") {
        document.getElementById("tab1_space").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        document.getElementById('InquiryHelp').innerHTML = getSelectedText('listboxInquiryId');
        //svuoto tutti i tab
        document.getElementById("tab2_space_Users_history").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        document.getElementById("tab2_space_Users_track").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        document.getElementById("tab3_ThreadMessage").innerHTML = "<div style=\"text-align: center\"></div>";
        document.getElementById("tab3_listThread").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        document.getElementById("tab4_space_report").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        document.getElementById("tab4_space").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        document.getElementById("tab5_space").innerHTML = "<div style=\"text-align: center\"><img src=\"Content/images/loading_icon.gif\" style=\"width: 140px; height: 124px; vertical-align: middle;align=center;\"></div>";
        tab("tab1");

        //alert(value);
        $.ajax({
            type: "GET",
            url: url + "/" + value,
            cache: false,
            //dataType: "xml",
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            data: "",
            success: function (response) {
                var testo = "<table>";
                testo += "<tr><td class='headerSpace'>Inquiry Members</td><td></td></tr>";
                var array_item = $(response).find("array_item");
                //<array_item type="array">
                //<oauthid type="string">642859267</oauthid>
                //<oauthprovider type="string">Facebook</oauthprovider>
                //<name type="string">Enrico Bruzzone</name>
                //</array_item>
                for (i = 0; i < array_item.length; i++) {
                    testo += "<tr>";

                    var oauthid = array_item[i].childNodes[0].textContent;
                    var oauthprovider = array_item[i].childNodes[1].textContent;
                    var name = array_item[i].childNodes[2].textContent;
                    var icon = array_item[i].childNodes[3].textContent;
                    //alert("Pippo: " + GetUserMail("Secure/GetUserMail", oauthid, oauthprovider));
                    var mail1 = GetUserMail("Secure/GetUserMail", oauthid, oauthprovider);
                    testo += "<td><img src='" + icon + "' height='35' width='35'> </td> <td style=\"color:rgb(90, 138, 198);font-family: Helvetica, Arial, sans-serif;font-size: 13px;font-weight: bold;\">" + name + " " + "<a href=\"mailto:" + mail1.responseText + "\">Send Mail</a> </td> ";
                    //if (i == 0) {
                    //    testo += "<td><select name=\"chooseFunctionality\" id=\"chooseFunctionality\" onchange=\"chooseTab('chooseFunctionality');\">  <option value=\"Select Action\">Select Action</option><option value=\"Track\">Track</option>  <option value=\"Show Path History\">Show Path History</option> <option value=\"Send Message\">Send Message</option>  <option value=\"Show Data\">Show Data</option> <option value=\"Assign Badges\">Assign Badges</option> </select></td>";
                    //}
                    //else testo += "<td></td>";

                    testo += "</tr>";
                }
                testo += "</table>";
                document.getElementById("tab1_space").innerHTML = testo;
            }
        });
        document.getElementById("tab1_descr").innerHTML = inquiryIdToDescription[value];
    }
}


//Nasconde e visualizza i tab
function tab(tabId, isPath) {
    //alert(SelectedUser);
    document.getElementById('tab1').style.display = 'none';
    document.getElementById('tab2').style.display = 'none';
    document.getElementById('tab3').style.display = 'none';
    document.getElementById('tab4').style.display = 'none';
    document.getElementById('tab5').style.display = 'none';

    document.getElementById('li_tab1').setAttribute("class", "");
    document.getElementById('li_tab2').setAttribute("class", "");
    document.getElementById('li_tab3').setAttribute("class", "");
    document.getElementById('li_tab4').setAttribute("class", "");
    document.getElementById('li_tab5').setAttribute("class", "");

    document.getElementById(tabId).style.display = 'block';
    
    document.getElementById('li_' + tabId).setAttribute("class", "active");

    document.getElementById('li_tab1').childNodes[0].style.background = '#f6f6f6';
    document.getElementById('li_tab2').childNodes[0].style.background = '#f6f6f6';
    document.getElementById('li_tab3').childNodes[0].style.background = '#f6f6f6';
    document.getElementById('li_tab4').childNodes[0].style.background = '#f6f6f6';
    document.getElementById('li_tab5').childNodes[0].style.background = '#f6f6f6';
    document.getElementById('li_' + tabId).childNodes[0].style.background = 'rgb(90, 138, 198)';

    if (tabId == 'tab2' && isPath == 1) {
        cambia('tab2_space_track');
        cleanMarker();
        //TO DO Deselezionare gli utenti ??
        GetUserMap('Secure/GetUserMap', 'UserOnMap', 'map_canvas', SelectedUser, document.getElementById('listboxInquiryId').value);
    }
    if (tabId == 'tab2' && isPath == 0) {
        cambia('tab2_space_history');
        cleanMarker();
        GetUserHistoryMap('Secure/GetUserHistoryMap', 'UserOnMap', 'map_canvas', SelectedUser);
    }
    if (tabId == 'tab3') {
        getThreadList('Secure/GetThreadList', document.getElementById('listboxInquiryId').value);
    }

    if (tabId == 'tab4') {
        getUserData('Secure/GetUserData', document.getElementById('listboxInquiryId').value);
    }
    if (tabId == 'tab5') {
        getUsersBadges('Secure/GetUsersBadges', document.getElementById('listboxInquiryId').value);
    }
}


function UserHistoryMap(idUtenteV, providerIdUtenteV)
{
    cambia('tab2_space_history');
    cleanMarker();
    GetUserHistoryMap('Secure/GetUserHistoryMap', 'UserOnMap', 'map_canvas', document.getElementById('listboxInquiryId').value, idUtenteV, providerIdUtenteV, '1970/01/01');
}


function HashTable(obj) {
    this.length = 0;
    this.items = {};
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            this.items[p] = obj[p];
            this.length++;
        }
    }

    this.setItem = function (key, value) {
        var previous = undefined;
        if (this.hasItem(key)) {
            previous = this.items[key];
        }
        else {
            this.length++;
        }
        this.items[key] = value;
        return previous;
    }

    this.getItem = function (key) {
        return this.hasItem(key) ? this.items[key] : undefined;
    }

    this.hasItem = function (key) {
        return this.items.hasOwnProperty(key);
    }

    this.removeItem = function (key) {
        if (this.hasItem(key)) {
            previous = this.items[key];
            this.length--;
            delete this.items[key];
            return previous;
        }
        else {
            return undefined;
        }
    }

    this.keys = function () {
        var keys = [];
        for (var k in this.items) {
            if (this.hasItem(k)) {
                keys.push(k);
            }
        }
        return keys;
    }

    this.values = function () {
        var values = [];
        for (var k in this.items) {
            if (this.hasItem(k)) {
                values.push(this.items[k]);
            }
        }
        return values;
    }

    this.each = function (fn) {
        for (var k in this.items) {
            if (this.hasItem(k)) {
                fn(k, this.items[k]);
            }
        }
    }

    this.clear = function () {
        this.items = {}
        this.length = 0;
    }
}


function loadMapUser(div_v, lat_v, lon_v, zoom_v) {
    var lat = lat_v;//47.35387;
    var lon = lon_v;//8.43609;
    var zoom = 18;

    var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
    var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
    var position = new OpenLayers.LonLat(lon, lat).transform(fromProjection, toProjection);

    //map = new OpenLayers.Map(div_v);
    //var mapnik = new OpenLayers.Layer.OSM();
    //map.addLayer(mapnik);

    var markers = new OpenLayers.Layer.Markers("Markers");
    map.addLayer(markers);
    markers.addMarker(new OpenLayers.Marker(position));

    map.setCenter(position, zoom);
}

//var position;
//var position1;
var fromProjection;
var toProjection;
var map;
var zoom;
var markers;
var HTOfMarkers = new HashTable();
var HTOfFeatures = new HashTable();
var renderer;
var vectorLayer;
var style = new OpenLayers.Style({
    fillColor: "#008000",
    strokeColor: "#000000",
    strokeWidth: 2
});

function createMap(div_v) {
    map = new OpenLayers.Map(div_v);
    var mapnik = new OpenLayers.Layer.OSM();
    map.addLayer(mapnik);
}

function setupMap(div_v) {
    //, lat_v, lon_v
    //var lat = lat_v;
    //var lon = lon_v;
    zoom = 15;
    fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
    toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection

    markers = new OpenLayers.Layer.Markers("Markers");
    map.addLayer(markers);
    var position = new OpenLayers.LonLat(9.1833, 45.4667).transform(fromProjection, toProjection);
    //position1 = new OpenLayers.LonLat(47.36387, 8.43609).transform(fromProjection, toProjection);
    map.setCenter(position, 5);


    // allow testing of specific renderers via "?renderer=Canvas", etc
    renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
    renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

    vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {
        styleMap: new OpenLayers.StyleMap({
            'default': {
                strokeColor: "#00FF00",
                strokeOpacity: 1,
                strokeWidth: 3,
                fillColor: "#FF5500",
                fillOpacity: 0.5,
                pointRadius: 4,
                pointerEvents: "visiblePainted",
                // label with \n linebreaks
                label: "${name}",
                //name: ${name} \n\nage: ${age}
                fontColor: "${favColor}",
                fontSize: "12px",
                fontFamily: "Courier New, monospace",
                fontWeight: "bold",
                labelAlign: "${align}",
                labelXOffset: "${xOffset}",
                labelYOffset: "${yOffset}",
                labelOutlineColor: "white",
                labelOutlineWidth: 3
            }
        }),
        renderers: renderer
    });
    map.addLayer(vectorLayer);
}

function AddUserToMap(div_v, lat_v, lon_v, userImg, chkBx, userId,userName) {
    //document.getElementById()
    if (document.getElementById(chkBx).checked == true) {


        // create a point feature
        var point = new OpenLayers.Geometry.Point(lon_v, lat_v);//.transform(fromProjection, toProjection);
        var pointFeature = new OpenLayers.Feature.Vector(point);
        pointFeature.attributes = {
            name: userName,
            fontSize : 12,
            //age: lon_v,
            favColor: 'red',
            align: "cm"
        };
        //vectorLayer.features[0]
        pointFeature.geometry.transform(fromProjection, toProjection);
        HTOfFeatures.setItem(userImg, pointFeature);
        vectorLayer.addFeatures(pointFeature);
        //var position = new OpenLayers.LonLat(lat_v, lon_v).transform(fromProjection, toProjection);
        var size = new OpenLayers.Size(24, 24);
        var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
        var icon = new OpenLayers.Icon(userImg, size, offset);
        var marker = new OpenLayers.Marker(new OpenLayers.LonLat(lon_v, lat_v).transform(fromProjection, toProjection), icon);

        markers.addMarker(marker);
        //markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(0,0),icon.clone()));

        HTOfMarkers.setItem(userImg, marker);
        var bounds = markers.getDataExtent();
        map.zoomToExtent(bounds);
    }
    else {
        var pointFeature = HTOfFeatures.getItem(userImg);
        vectorLayer.removeFeatures(pointFeature);

        var marker = HTOfMarkers.getItem(userImg);
        markers.removeMarker(marker);
        var position = new OpenLayers.LonLat(9.1833, 45.4667).transform(fromProjection, toProjection);
        map.setCenter(position, 5);
    }

}

function cleanMarker() {
    HTOfMarkers.clear();
    markers.clearMarkers();
    vectorLayer.removeAllFeatures();
}

function AddHistoryPointToMap(div_v, lat_v, lon_v, userImg, descr, sequential) {

    // create a point feature
    var point = new OpenLayers.Geometry.Point(lon_v, lat_v);//.transform(fromProjection, toProjection);
    var pointFeature = new OpenLayers.Feature.Vector(point);
    pointFeature.attributes = {
        name: sequential,
        fontSize: 12,
        //age: lon_v,
        favColor: 'red',
        align: "cm"
    };
    //vectorLayer.features[0]
    pointFeature.geometry.transform(fromProjection, toProjection);
    vectorLayer.addFeatures(pointFeature);

    var size = new OpenLayers.Size(24, 24);
    var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
    var icon = new OpenLayers.Icon(userImg, size, offset);
    var marker = new OpenLayers.Marker(new OpenLayers.LonLat(lon_v, lat_v).transform(fromProjection, toProjection), icon);//
  

    markers.addMarker(marker);

    HTOfMarkers.setItem(userImg, marker);
    var bounds = markers.getDataExtent();
    map.zoomToExtent(bounds);


}

//http://stackoverflow.com/questions/9765224/draw-line-between-two-points-using-openlayers
/*
function createMarkersAndCenterMap(div_v, lat_v, lon_v) {

    markers.addMarker(new OpenLayers.Marker(position));

    var markers1 = new OpenLayers.Layer.Markers("Markers1");
    map.addLayer(markers1);
    markers1.addMarker(new OpenLayers.Marker(position1));

    var ol = new OpenLayers.Layer.OSM();

    var start_point = new OpenLayers.Geometry.Point(47.35387, 8.43609);
    var end_point = new OpenLayers.Geometry.Point(47.36387, 8.43609);
    var vector = new OpenLayers.Layer.Vector();
    vector.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([start_point, end_point]).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")))]);
    map.addLayers([ol, vector]);

    map.setCenter(position, zoom);
}
*/
/*
 function settaImmagine(div_v, lat_v, lon_v) {
     setupMap(div_v, lat_v, lon_v);
     createMarkersAndCenterMap(div_v, lat_v, lon_v);
 }
 */

function littleImg(x) {
    x.style.height = "30px";
    x.style.width = "30px";
}

function normalImg(x) {
    x.style.height = "35px";
    x.style.width = "35px";
}

function littleThumb(x) {
    x.style.height = "68px";
    x.style.width = "68px";
}

function normalThumb(x) {
    x.style.height = "72px";
    x.style.width = "72px";
}

function littleDiv(x) {
    x.style.height = "45px";
    x.style.width = "72px";
}

function normalDiv(x) {
    x.style.height = "50px";
    x.style.width = "80px";
}